package com.kll.carolinehmibiz.net

import androidx.annotation.NonNull
import com.kll.carolinehmibiz.net.listener.DownloadListener
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*
import java.io.IOException


/**
 * ====================================================
 * Created by Ziliang Cai on 2022/1/3 4:27 下午
 * <a href="mailto:752577456@qq.com">Contact me</a>
 * ====================================================
 */
class DownloadResponseBody: ResponseBody {

    val responseBody: ResponseBody
    private var bufferedSource: BufferedSource? = null

    constructor(responseBody: ResponseBody, listener: DownloadListener?) {
        this.responseBody = responseBody
        listener?.onStart(responseBody)
    }

    override fun contentType(): MediaType? {
        return responseBody.contentType();
    }

    override fun contentLength(): Long {
        return responseBody.contentLength();
    }

    override fun source(): BufferedSource {
        if (bufferedSource == null) {
            bufferedSource = Okio.buffer(getSource(responseBody.source()));
        }
        return bufferedSource!!
    }

    private fun getSource(source: Source): Source? {
        return object : ForwardingSource(source) {
            var downloadBytes = 0L

            @Throws(IOException::class)
            override fun read(@NonNull buffer: Buffer?, byteCount: Long): Long {
                val singleRead = super.read(buffer, byteCount)
                if (-1L != singleRead) {
                    downloadBytes += singleRead
                }
                return singleRead
            }
        }
    }
}